package com.coy.web.service.impl;

import com.alibaba.fastjson.JSON;
import com.coy.web.common.consts.WebConsts;
import com.coy.web.common.dto.DataResult;
import com.coy.web.common.exception.BizResultCode;
import com.coy.web.common.util.security.MD5;
import com.coy.web.dao.service.IUserInfoService;
import com.coy.web.feign.dto.RegAndLoginReq;
import com.coy.web.feign.dto.UpdatePwdReq;
import com.coy.web.service.ILoginService;
import com.coy.web.util.SessionUtil;
import com.coy.web.zax.feign.dto.UserInfoDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * @author chenck
 * @date 2021/6/12 22:04
 */
@Service
public class LoginServiceImpl implements ILoginService {

    @Resource
    IUserInfoService userInfoService;

    @Override
    public DataResult<UserInfoDTO> login(RegAndLoginReq req) {
        if (StringUtils.isBlank(req.getPassword()) && StringUtils.isBlank(req.getSmsCode())) {
            return DataResult.error(BizResultCode.ERR_PARAM.getCode(), "请传入密码或短信验证码");
        }
        // 查询用户
        DataResult<UserInfoDTO> result = userInfoService.queryUser(req.getPhone());
        if (!result.isSucc()) {
            return result;
        }
        UserInfoDTO userInfoDTO = result.getData();
        if (null == userInfoDTO) {
            return DataResult.error(BizResultCode.ERR_USER_NOT_EXIST.getCode(), "用户不存在");
        }

        // 密码校验
        if (StringUtils.isNotBlank(req.getPassword())) {
            String password = MD5.encode(req.getPassword());
            if (!password.equals(userInfoDTO.getPassword())) {
                return DataResult.error("密码错误");
            }
        }

        // 短信验证码校验
        if (StringUtils.isNotBlank(req.getSmsCode())) {
            // TODO 对接短信平台
            return DataResult.error(BizResultCode.ERR_SYSTEM.getCode(), "暂不支持短信验证码登录");
        }

        // 登录
        HttpSession session = SessionUtil.getSession();
        session.setAttribute(WebConsts.SESSION_KEY_USER, JSON.toJSONString(userInfoDTO));
        return result;
    }

    @Override
    public DataResult updatePwd(UpdatePwdReq req) {
        return userInfoService.updatePwd(req);
    }
}
